package com.bw.common.view

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.SweepGradient
import android.graphics.Typeface
import android.util.AttributeSet
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.core.content.ContextCompat
import com.bw.common.R
import kotlin.math.min

class CircleCountDownView @JvmOverloads constructor(context: Context,attrs:AttributeSet?=null,defaultStyle:Int=0):View(context,attrs,defaultStyle){

   private var progressColor =Color.BLUE
   private var progressBackgroundColor =Color.LTGRAY
   private var progressWidth=20F
   private var textColor =Color.BLACK
   private var textSize =40F
   private var countDownTime =5
   private var textY=0F


    private var centerX=0f
    private var centerY=0f
    private var radius=0f

    private var sweepAngle=0f
    private var currentAngle=0f

    private var remainingTime=countDownTime//剩余时间
    private var animator:ValueAnimator?=null
    private var countDownLister :CountDownLister?=null

     //背景画笔样式
    private val backgroundPaint =Paint(Paint.ANTI_ALIAS_FLAG).apply {
       style=Paint.Style.STROKE
         color=progressBackgroundColor
         strokeWidth=progressWidth
         strokeCap=Paint.Cap.ROUND
    }
    //进度条画笔
    private val progressPaint =Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style=Paint.Style.STROKE
        color=progressColor
        strokeWidth=progressWidth
        strokeCap=Paint.Cap.ROUND
    }
    //进度条底色画笔
    private val gradientPaint =Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style=Paint.Style.STROKE
        strokeWidth=progressWidth
        strokeCap=Paint.Cap.ROUND
        shader=SweepGradient(centerX,centerY, intArrayOf(Color.RED,Color.YELLOW,Color.GREEN),null)
    }

    //文本画笔
    private val textPaint =Paint(Paint.ANTI_ALIAS_FLAG).apply {
       color=textColor
        textSize=textSize
        textAlign=Paint.Align.CENTER
        typeface=Typeface.DEFAULT_BOLD
    }



    init {
        attrs?.run {
            //获取自定义属性
            val typeArray=context.obtainStyledAttributes(this, R.styleable.CircleCountDownView)
             progressColor =typeArray.getColor(R.styleable.CircleCountDownView_progressColor,ContextCompat.getColor(context,R.color.blueviolet))
             progressBackgroundColor =typeArray.getColor(R.styleable.CircleCountDownView_progressColor,ContextCompat.getColor(context,R.color.alpha_white))
             progressWidth =typeArray.getDimension(R.styleable.CircleCountDownView_progressWidth,20F)
             textColor =typeArray.getColor(R.styleable.CircleCountDownView_progressColor,Color.BLACK)
             textSize =typeArray.getDimension(R.styleable.CircleCountDownView_textSize,40F)
             countDownTime =typeArray.getInteger(R.styleable.CircleCountDownView_countDownTime,5)

            //释放资源，避免内存泄漏
            typeArray.recycle()
        }

        //重置画笔属性
        backgroundPaint.strokeWidth=progressWidth
        progressPaint.strokeWidth=progressWidth
        gradientPaint.strokeWidth=progressWidth
        textPaint.color=textColor
        textPaint.textSize=textSize
        //剩余时间
        remainingTime=countDownTime

    }
    fun setCountDownLister(l:CountDownLister){
        countDownLister=l
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        centerX=w/2F
        centerY=h/2F

        radius=(min(w,h)-progressWidth)/2f
    }

    /**
     * 不要在onDraw方法中创建临时变量或对象，避免内存抖动
     * 不要做复杂计算
     */
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        //绘制圆形北京
        canvas.drawCircle(centerX,centerY,radius,backgroundPaint)

        //绘制进度
        sweepAngle = 360 * (currentAngle/100f)
        canvas.drawArc(centerX-radius,centerY-radius,centerX+radius,centerY+radius,-90f,sweepAngle,false,gradientPaint)

        //绘制文本
        textY =centerY-(textPaint.descent() + textPaint.ascent()) /2
        canvas.drawText("${remainingTime}s跳过",centerX,textY,textPaint)

    }
    //开启倒计时
    fun startCountDown(){
       animator= ValueAnimator.ofFloat(0f,100f).apply {
           duration=(countDownTime*1000).toLong()
           interpolator=LinearInterpolator()//匀速执行动画
           //添加监听事件
           addUpdateListener {
               currentAngle=it.animatedValue as Float
               remainingTime=countDownTime-((currentAngle/100f) * countDownTime).toInt()
               //重新绘制UI
               invalidate()

               //倒计时结束
               if (remainingTime==0){
                   countDownLister?.countDownFinished()
               }
           }
       }
        //执行动画
        animator?.start()
    }
    //关闭倒计时
    fun stopCountDown(){
        animator?.cancel()
        animator=null
    }

    /**
     * 当组件从窗口解绑时回调
     */
    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        stopCountDown()
    }


    /**
     * 定义接口
     */
    interface CountDownLister{
        fun countDownFinished()
    }
}
